import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import axios from 'axios';
import qs from 'qs';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Input,
  Spin,
  Pagination,
  Table,
  Drawer,
  Form,
  Select,
  Button,
  Switch,
} from 'antd';
import styles from './index.less';
import editImg from '@/assets/basic/customDictionary/xiazi.png';
import sy from '@/assets/basic/customDictionary/sy.png';
import bianji from '@/assets/basic/customDictionary/bianji.png';
import edit from '@/assets/basic/customDictionary/edit.png';
import moreImg from '@/assets/knowledge/more.png';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';
import append from '@/assets/account/roleManagement/append.png';
import checkimg from '@/assets/account/authorization/check.png';
import editIcon from '@/assets/account/authorization/editIcon.png';
import query from '@/assets/account/authorization/query.png';
import Check from './check';
import Accredit from './accredit';

const Search = Input.Search;
const FormItem = Form.Item;
const { Option } = Select;

class Authorization extends Component {
  state = {
    list: [],
    total: '',
    login: false,
    total: '12',
    current: 1,
    pageSize: 10,
    addModel: false,
    addModelRedact: null,
    isEffect: '',
    flowState: '',
    itemObj: '',
    twospin:false,
    namelist:[],
    startSetone:'',
    roleName:''
  };

  componentDidMount() {
    const { dispatch, sysgetmenusByUserId } = this.props;
    this.getRolesByStatusAndIsEnablemenusByUserId();
    this.getRolesByStatusAndIsEnablemenusByUserIdtwo();
  }

  unique5 = arr => {
    let x = new Set(arr);
    return [...x];
  };


  ceshi = index => {
    const { current, pageSize } = this.state;
    let a = (current - 1) * pageSize + index + 1;
    return a;
  };

  getRolesByStatusAndIsEnablemenusByUserId = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { pageSize,current,startSetone,roleName } = this.state;
    console.log(currentUser);
    const userVo = {
      createUserId: currentUser.uid,
      page:current,
      rows:pageSize,
      // uStatus:'0',
      //  uStatus: startSetone,
      roleName,
    };
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'authorization/getRoleByStatusOrCreateByPage',
        payload: userVo,
        callback: res => {
          console.log(res);
          res.data.list.map((item)=>{
            item.status = item.userStatus==='0'?false:true
          })
          this.setState({
            login: false,
            list: res.data.list,
            total:res.data.total,
          });
        },
      });
    });
  };

  getRolesByStatusAndIsEnablemenusByUserIdtwo = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { pageSize,current,startSetone,roleName } = this.state;
    console.log(currentUser);
    const userVo = {
      createUserId: currentUser.uid,
      page:current,
      rows:10000,
      // uStatus:'0',
      //  uStatus: startSetone,
      roleName,
    };
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'authorization/getRoleByStatusOrCreateByPage',
        payload: userVo,
        callback: res => {
          console.log(res);
          let namelist = ['全部'];
          res.data.list.map(item => {
            namelist.push(item.roleName);
          });
          this.setState({
            login: false,
            namelist: this.unique5(namelist),
          });
        },
      });
    });
  };

  

  onChangeTable = a => {
    console.log(a);
    this.setState({current:a},()=>{
      this.getRolesByStatusAndIsEnablemenusByUserId()
    })
  };

  onShowSizeChangeTable = (a, b) => {
    console.log(a, b);
    this.setState({current:a,pageSize:b},()=>{
      this.getRolesByStatusAndIsEnablemenusByUserId()
    })
  };

  onClosebj = () => {
    this.setState({
      addModel: false,
    });
  };

  append = item => {
    // 查看
    this.sysgetMenuList(item.roleId);
    this.setState({
      addModel: true,
      addModelRedact: '1',
      itemListObj: item,
    });
  };

  Redact = item => {
    this.sysgetMenuList(item.roleId);
    this.setState({
      addModel: true,
      addModelRedact: '2',
      itemListObj: item,
    });
  };

  operation = () => {
    // console.log
  };

  // 下拉框
  handleChangeSelect = value => {
    console.log(`selected ${value}`);
    this.setState({ isEffect: value === '生效' ? '1' : '0' });
  };

  handleChangeState = value => {
    console.log(`selected ${value}`);
    let {roleName} = this.state;
    if(value === '全部'){
      roleName = null
      this.setState({ roleName });
    }else{
      this.setState({ roleName:value });
    }
  
  };

  rktbonChange = (item, index) => {
    console.log(item, index);
    const { list } = this.state;
    list[index].start = !item.start;
    this.setState({ list }, () => {
      console.log(this.state.list);
    });
  };

  sysgetMenuList = roleId => {
    this.setState({twospin:true})
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'authorization/sysgetMenuList',
        payload: {roleId:roleId },
        callback: res => {
          console.log('菜单列表', res);
          this.setState({
            itemObj: res.data?res.data:[],
            twospin:false,
          });
        },
      });
    });

    // const { dispatch, currentUser } = this.props;
    // console.log(currentUser, '222');
    // let api = '/cloud/new/sys/getMenuList';
    // const obj = { roleId: currentUser.robotId };
    // const params = qs.stringify(obj);
    // const newUrl = api + '?' + params;
    // const token =
    //   JSON.parse(window.localStorage.getItem('currentUser')) == undefined
    //     ? ''
    //     : JSON.parse(window.localStorage.getItem('currentUser')).token;
    // // const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId")) ;
    // const headData = { 'Content-Type': 'application/json', token: token };
    // return new Promise(resolve => {
    //   axios.post(newUrl, obj, { headers: headData }).then(res => {
    //     console.log(res.data.data, '--');
    //     this.setState({
    //       itemObj: res.data.data?res.data.data:[],
    //     });
    //   });
    // });
  };

  itemObjfa =(item) => {
    console.log(item)
    this.setState({itemObj:item})
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { addModelRedact, itemObj, itemListObj,twospin } = this.state;
    const operationDate = [
      {
        title: '序号',
        width: '200px',
        align: 'center',
        render: (item, todo, index) => {
          return <span>{this.ceshi(index)}</span>;
        },
      },
      {
        title: '角色名称',
        dataIndex: 'roleName',
        align: 'center',
        // width: '200px',
      },
      {
        title: '上次修改时间',
        dataIndex: 'updateTime',
        align: 'center',
        // width: 'calc(15vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{moment(Number(item)).format('YYYY-MM-DD h:mm:ss')}</span>
            </div>
          );
        },
      },
      {
        title: '',
        width: '250px',
        align: 'center',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div className={styles.tool}>
                <img onClick={() => this.Redact(item)} src={checkimg} />
                <img onClick={() => this.append(item)} style={{ marginLeft: 15 }} src={editIcon} />
              </div>
              <img src={moreImg} className={styles.more} />
            </div>
          );
        },
      },
    ];
    return (
      <div>
        <Spin spinning={this.state.login}>
          <div className={styles.backgroundp}>
            <p style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
              权限管理
            </p>
            <div className={styles.imgbj}>
              <div>
                {/* <Select
                  size="large"
                  placeholder="是否生效"
                  style={{ width: 200 }}
                  onChange={this.handleChangeSelect}
                >
                  <Option value="生效">生效</Option>
                  <Option value="不生效">不生效</Option>
                </Select>
                <Select
                  size="large"
                  placeholder="状态"
                  style={{ width: 200, margin: '0px 20px' }}
                  onChange={this.handleChangeState}
                >
                  <Option value="在线">在线</Option>
                  <Option value="离线">离线</Option>
                </Select> */}
                <Select
                size="large"
                placeholder="角色名称"
                showSearch
                style={{ width: 200, margin: '0px 20px 0px 0px' }}
                onChange={this.handleChangeState}
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {this.state.namelist.map((item, index) => {
                  return <Option value={item}>{item}</Option>;
                })}
              </Select>
                <img
                  onClick={this.getRolesByStatusAndIsEnablemenusByUserId}
                  style={{ position: 'relative', top: 3, cursor: 'pointer' }}
                  src={query}
                />
              </div>
              {/* <div>
              <img onClick={this.append} src={append} />
            </div> */}
            </div>
            <div style={{ height: 20 }} />
            {/* <Spin spinning={this.state.login}> */}
            <div className={styles.dabj} style={{ padding: '0px 20px' }}>
              <div className={styles.border} style={{ position: 'relative', right: '2px' }}>
                <Table
                  className="zdyTable"
                  columns={operationDate}
                  dataSource={this.state.list} //数据
                  pagination={false}
                />
              </div>
            </div>
            <Pagination
              style={{ textAlign: 'center', marginTop: 20 }}
              total={this.state.total}
              pageSize={this.state.pageSize} // 显示几条一页
              current={this.state.current} // 当前页
              showSizeChanger={true} // 是否显示可以设置几条一页的选项
              onChange={this.onChangeTable}
              onShowSizeChange={this.onShowSizeChangeTable}
              showTotal={() => `共 ${this.state.total} 条`}
            />
            {/* </Spin> */}
          </div>
          <Drawer
            className="zdyset"
            title={
              <span>
                <Icon
                  style={{ cursor: 'pointer' }}
                  onClick={this.onClosebj}
                  style={{ marginRight: 20 }}
                  type="arrow-left"
                />
                {addModelRedact === '2' ? '查看' : '授权'}
              </span>
            }
            placement="right"
            closable={false}
            onClose={this.onClosebj}
            visible={this.state.addModel}
            width="calc(100vw - 245px)"
            destroyOnClose
          >
            {addModelRedact === '1' ? (
              <Accredit itemObjfa={this.itemObjfa}  twospin={twospin} itemListObj={itemListObj} itemObj={itemObj} />
            ) : (
              <Check itemObjfa={this.itemObjfa} twospin={twospin} itemListObj={itemListObj} itemObj={itemObj} />
            )}
          </Drawer>
        </Spin>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(Authorization));
